// src/nodes/InputNode.js
import React, { useCallback, useRef, useState } from 'react';
import { Handle } from 'reactflow';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import {
  faFileLines,
  faCalculator,
  faCheckDouble,
  faCode,
  faFlask,
  faTriangleExclamation,
  faCopy
} from '@fortawesome/free-solid-svg-icons';

const typeIcons = {
  string: faFileLines,
  number: faCalculator,
  boolean: faCheckDouble,
  json: faCode
};

const InputNode = ({ data, id }) => {
  const fileInputRef = useRef(null);
  const icon = typeIcons[data.inputType] || faFlask;
  const [localValue, setLocalValue] = useState(data.content);
  const [isComposing, setIsComposing] = useState(false);

  const copyNodeId = () => {
    navigator.clipboard.writeText(id)
      .catch(err => console.error('Failed to copy:', err));
  };

  const handleFileChange = useCallback((e) => {
    const file = e.target.files[0];
    if (!file) return;

    const reader = new FileReader();
    reader.onload = (event) => {
      data.onChange(event.target.result);
    };
    reader.readAsText(file);
  }, [data]);

  const renderInput = () => {
    switch (data.inputType) {
      case 'boolean':
        return (
          <select
            value={data.content}
            onChange={(e) => data.onChange(e.target.value)}
            onDoubleClick={(e) => e.stopPropagation()}
            className={`w-full px-3 py-2 text-sm bg-white/90 backdrop-blur-sm 
              rounded-lg border-2 transition-all duration-200
              focus:ring-4 focus:ring-emerald-400/30 focus:border-emerald-500
              ${data.error ? 'border-rose-500' : 'border-slate-200 hover:border-slate-300'}`}
          >
            <option value="true">true</option>
            <option value="false">false</option>
          </select>
        );
      
      case 'number':
        return (
          <input
            type="number"
            value={data.content}
            onChange={(e) => data.onChange(e.target.value)}
            onDoubleClick={(e) => e.stopPropagation()}
            placeholder="输入数字..."
            className={`w-full px-3 py-2 text-sm bg-white/90 backdrop-blur-sm
              rounded-lg border-2 transition-all duration-200
              focus:ring-4 focus:ring-emerald-400/30 focus:border-emerald-500
              ${data.error ? 'border-rose-500' : 'border-slate-200 hover:border-slate-300'}`}
          />
        );

      case 'json':
        return (
          <div className="flex flex-col gap-3">
            <textarea
              value={localValue}
              onChange={(e) => {
                setLocalValue(e.target.value);
                if (!isComposing) {
                  data.onChange(e.target.value);
                }
              }}
              onCompositionStart={() => setIsComposing(true)}
              onCompositionEnd={(e) => {
                console.log('onCompositionEnd');
                setIsComposing(false);
                data.onChange(e.target.value);
              }}
              onDoubleClick={(e) => e.stopPropagation()}
              placeholder="输入 JSON..."
              className={`w-full px-3 py-2 text-sm bg-white/90 backdrop-blur-sm 
                rounded-lg border-2 resize-y transition-all duration-200 min-h-[100px]
                focus:ring-4 focus:ring-emerald-400/30 focus:border-emerald-500
                ${data.error ? 'border-rose-500' : 'border-slate-200 hover:border-slate-300'}`}
            />
            <button
              className="self-end px-4 py-1.5 text-sm font-medium bg-gradient-to-r from-emerald-500 to-teal-500 
                text-white rounded-lg hover:shadow-lg transition-all duration-200
                hover:from-emerald-600 hover:to-teal-600 active:scale-95 shadow-sm"
              onClick={() => fileInputRef.current.click()}
              onDoubleClick={(e) => e.stopPropagation()}
            >
              上传JSON文件
            </button>
          </div>
        );

      default: // 字符串类型处理
        return (
          <div className="flex flex-col gap-3">
            <textarea
              value={localValue}
              onChange={(e) => {
                setLocalValue(e.target.value);
                if (!isComposing) {
                  data.onChange(e.target.value);
                }
              }}
              onCompositionStart={() => setIsComposing(true)}
              onCompositionEnd={(e) => {
                console.log('onCompositionEnd');
                setIsComposing(false);
                data.onChange(e.target.value);
              }}
              onDoubleClick={(e) => e.stopPropagation()}
              placeholder="输入文本..."
              className={`w-full px-3 py-2 text-sm bg-white/90 backdrop-blur-sm 
                rounded-lg border-2 resize-y transition-all duration-200 min-h-[100px]
                focus:ring-4 focus:ring-emerald-400/30 focus:border-emerald-500
                ${data.error ? 'border-rose-500' : 'border-slate-200 hover:border-slate-300'}`}
            />
            <button
              className="self-end px-4 py-1.5 text-sm font-medium bg-gradient-to-r from-emerald-500 to-teal-500 
                text-white rounded-lg hover:shadow-lg transition-all duration-200
                hover:from-emerald-600 hover:to-teal-600 active:scale-95 shadow-sm"
              onClick={() => fileInputRef.current.click()}
              onDoubleClick={(e) => e.stopPropagation()}
            >
              上传文本文件
            </button>
          </div>
        );
    }
  };

  return (
    <div 
      className="p-5 rounded-xl shadow-xl w-80 bg-gradient-to-br from-white to-slate-50/80
        backdrop-blur-sm border-2 border-slate-100 hover:shadow-2xl transition-all duration-200
        group relative hover:border-slate-200"
    >
      {/* Header */}
      <div className="flex items-center mb-3 gap-3 min-w-0">
        <div className="p-2.5 bg-gradient-to-br from-emerald-500 to-teal-500 rounded-lg shadow-sm">
          <FontAwesomeIcon 
            icon={icon}
            className="w-5 h-5 text-white"
          />
        </div>
        <h3 className="text-base font-semibold text-slate-700 truncate flex-1 min-w-0">{data.label}</h3>
      </div>
      <div className="flex items-center gap-1 text-xs text-gray-500 mt-1 mb-2">
        <p className="overflow-hidden truncate">nodeID: {id}</p>
        <FontAwesomeIcon 
          icon={faCopy}
          className="text-gray-400 hover:text-blue-500 cursor-pointer ml-1"
          onClick={(e) => {
            e.stopPropagation();
            copyNodeId();
          }}
          title="复制节点ID"
        />
      </div>

      {/* Type Selector */}
      <select
        value={data.inputType}
        onChange={(e) => data.onTypeChange(e.target.value)}
        className="w-full px-3 py-2 mb-3 text-sm bg-white border-2 border-slate-200
          rounded-lg transition-all duration-200 hover:border-slate-300
          focus:ring-4 focus:ring-emerald-400/30 focus:border-emerald-500"
        onDoubleClick={(e) => e.stopPropagation()}
      >
        <option value="string">字符串</option>
        <option value="number">数字</option>
        <option value="boolean">布尔值</option>
        <option value="json">JSON</option>
      </select>

      {/* Input Area */}
      {renderInput()}

      <input
        type="file"
        ref={fileInputRef}
        className="hidden"
        onChange={handleFileChange}
        accept={data.inputType === 'json' ? '.json' : '.txt,.text'}
      />

      {/* Error Message */}
      {data.error && (
        <div className="mt-3 p-2.5 bg-rose-50/90 border border-rose-200 rounded-lg flex items-center gap-2">
          <FontAwesomeIcon 
            icon={faTriangleExclamation} 
            className="w-4 h-4 text-rose-500" 
          />
          <span className="text-sm text-rose-600">{data.error}</span>
        </div>
      )}

      {/* Handle */}
      <Handle
        id="output"
        type="source"
        position="right"
        className="!w-4 !h-4 !bg-blue-500"
      />
    </div>
  );
};

export const validateInput = (type, value) => {
  if (type === 'number') {
    const isValid = !isNaN(value) && value.trim() !== '';
    return isValid ? null : '请输入有效数字';
  }
  
  if (type === 'boolean') {
    return value === 'true' || value === 'false' 
      ? null 
      : '请选择 true/false';
  }

  if (type === 'json') {
    try {
      JSON.parse(value);
      return null;
    } catch {
      return '请输入有效 JSON';
    }
  }

  return null;
};

export default InputNode;